package com.swmaestro.twar;

import java.util.StringTokenizer;

import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.Hours;
import org.joda.time.Minutes;

public class Utils {
	
	public static String uniToStr(String uni) {
		String str = "";
		
		StringTokenizer st = new StringTokenizer(uni, "\\u");
		
		while(st.hasMoreTokens()) {
			String str1 = st.nextToken();
			int i = Integer.parseInt(str1, 16);
			str += (char)i;
		}
		return str;
	}
	
	public static DateTime convertString2DateTime(String str) {
		int years = Integer.valueOf(str.substring(0,4));
		int months = Integer.valueOf(str.substring(5,7));
		int days = Integer.valueOf(str.substring(8,10));
		int hours = Integer.valueOf(str.substring(11,13));
		int minutes = Integer.valueOf(str.substring(14,16));
		
		return new DateTime(years, months, days, hours, minutes);
	}
	
	public static String convertDateTime2String(DateTime dt_now, boolean includeTime) {
		int years = dt_now.getYear();
		int months = dt_now.getMonthOfYear();
		int days = dt_now.getDayOfMonth();
		
		StringBuilder now_sb = new StringBuilder();
		
		now_sb.append(years);
		now_sb.append("-");
		if(months < 10) now_sb.append(0);
		now_sb.append(months);
		now_sb.append("-");
		if(days < 10) now_sb.append(0);
		now_sb.append(days);
		
		if(includeTime) {
			int hours = dt_now.getHourOfDay();
			int minutes = dt_now.getMinuteOfHour();
			
			now_sb.append(" ");
			if(hours < 10) now_sb.append(0);
			now_sb.append(hours);
			now_sb.append(":");
			if(minutes < 10) now_sb.append(0);
			now_sb.append(minutes);
		}
		
		return now_sb.toString();
	}
	
	public static String convertDateTime2String(DateTime dt_this, DateTime dt_now) {
		int days = Days.daysBetween(dt_this, dt_now).getDays();
		int hours = Hours.hoursBetween(dt_this, dt_now).getHours();
		int minutes = Minutes.minutesBetween(dt_this, dt_now).getMinutes();
		
		if(days > 3) {
			return convertDateTime2String(dt_this, false);
		} else if(days == 2 || days == 3) {
    			String str_days_ago = " days ago";
			//multi
			return days + str_days_ago;
		} else if(days == 1){
			String str_yesterday = "yesterday";
			//multi
			return str_yesterday;
		} else if(hours != 0) {
			if(hours == 1) {
				String str_an_hour_ago = "an hour ago";
				//multi
				return str_an_hour_ago;
			} else {
        		String str_hours_ago = " hours ago";
				//multi
        		return hours + str_hours_ago;
			}
		} else if(minutes != 0) {
			if(minutes == 1) {
				String str_a_minute_ago = "a minute ago";
				//multi
				return str_a_minute_ago;
			} else {
        		String str_minutes_ago = " minutes ago";
				//multi
        		return minutes + str_minutes_ago;
			}
		} else {
			String str_right_now = "right now";
			//multi
			return str_right_now;
		}
	}
}
